package org.iartisan.wechatsdk.miniprogram

import org.iartisan.runtime.env.EnvContextConfig
import org.iartisan.runtime.utils.HttpRequestUtil
import org.iartisan.wechatsdk.Utils._
import org.iartisan.wechatsdk.common.Constant
import org.iartisan.wechatsdk.miniprogram.res.{Code2SessionRes, WechatPhoneNumber, WechatUserInfo}

/**
  * 小程序授权方法
  *
  * @author King  2019/6/17
  */
object AuthService {

  private val AUTH_CODE2SESSION = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"

  def code2Session(code: String) = {
    val appId = EnvContextConfig.get(Constant.wechat_miniapp_appid)
    val secret = EnvContextConfig.get(Constant.wechat_miniapp_secret)
    val request = String.format(AUTH_CODE2SESSION, appId, secret, code)
    val res = HttpRequestUtil.sendGet(request)
    val result = Option(res.toObject[Code2SessionRes])
    //如果没有解析出来errorcode 则请求是成功的
    result.get
  }

  def getUserInfo(encryptedData: String, sessionKey: String, iv: String, appid: String) = {
    val json = WXBizDataCrypt.decrypt(encryptedData, sessionKey, iv)
    val info = json.toObject[WechatUserInfo]
    if (!info.getWatermark.getAppid.equals(appid)) throw new IllegalArgumentException("-41003,非法密文")
    info
  }

  /**
    * 获取用户手机号
    *
    * @param encryptedData
    * @param sessionKey
    * @param iv
    * @param appid
    * @return
    */
  def getPhoneNumber(encryptedData: String, sessionKey: String, iv: String, appid: String) = {
    val json = WXBizDataCrypt.decrypt(encryptedData, sessionKey, iv)
    val info = json.toObject[WechatPhoneNumber]
    if (!info.getWatermark.getAppid.equals(appid)) throw new IllegalArgumentException("-41003,非法密文")
    info
  }
}
